import cv2
import numpy as np

if __name__ == '__main__':
    # 读取图像,直接使用参数cv2.IMREAD_GRAYSCALE来读取灰度图像
    gray = cv2.imread('opencv_logo.jpg', cv2.IMREAD_GRAYSCALE)

    _,binary = cv2.threshold(gray,200,255,cv2.THRESH_BINARY_INV)

    # 显示图像
    cv2.imshow('binary', binary)

    # 定义内核
    kernel = np.ones((5,5),np.uint8)
    # 腐蚀 参数1 输入图像 参数2 内核 参数3 迭代次数
    erosion = cv2.erode(binary,kernel,iterations = 1)
    # 膨胀 参数1 输入图像 参数2 内核 参数3 迭代次数
    dilation = cv2.dilate(erosion,kernel,iterations = 1)

    # 显示图像
    cv2.imshow('erosion', erosion)
    cv2.imshow('dilation', dilation)

    # 等待按键
    if cv2.waitKey(0) & 0xFF == ord('q'):
        cv2.destroyAllWindows()
    # 退出程序
    exit(0)